﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Components_Search : System.Web.UI.UserControl
{
    DatabaseHelper helper;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                Utils.loadProductType(cboProductType, 1);
                if (Request.Cookies["ParamSearch"] != null)
                {
                    string strValue = Utils.KillChars(Request.Cookies["ParamSearch"].Value.ToString());
                    string[] arrParam = strValue.Trim().Split('@');
                    
                    loadProduct(arrParam[0], arrParam[1] == "" ? -1 : Convert.ToInt32(arrParam[1]), arrParam[2] == "" ? 0 : Convert.ToDouble(arrParam[2]), arrParam[3] == "" ? 500000 : Convert.ToDouble(arrParam[3]));
                    txtProductName.Text = arrParam[0];
                    cboProductType.SelectedValue = arrParam[1];
                    txtPriceFrom.Text = String.Format("{0:N0}", Convert.ToDouble(arrParam[2]));
                    txtPriceTo.Text = String.Format("{0:N0}", Convert.ToDouble(arrParam[3]));
                }
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("Search Page-IsPostBack:" + ex.Message);
            }
        }
    }
    protected void btnOrder_Command(object sender, CommandEventArgs e)
    {
        try
        {
            //San pham dat hang
            if (e.CommandArgument != null)
            {
                /*TODO*/
                string str = e.CommandArgument.ToString();
                string[] arrListProduct = str.Split('@');
                int iProductID = Convert.ToInt32(arrListProduct[0]);
                string strProductName = arrListProduct[1];
                string strProductCode = arrListProduct[2];
                string strImagePath = arrListProduct[3];
                double dPrice = Convert.ToDouble(arrListProduct[4]);
                int iWeight = 1;
                string strIsPromotion = arrListProduct[5];
                createCartTable(iProductID, strProductName, strProductCode, strImagePath, dPrice, iWeight, Convert.ToInt32(strIsPromotion));
                Response.Redirect(Request.UrlReferrer.AbsolutePath, false);
            }
            else
            {
                /*TODO*/
                ControlUtil.LogError("Search Page-btnOrder_Command");
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Search Page-btnOrder_Command:" + ex.Message);
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            string strProductName = Utils.KillChars(txtProductName.Text.Trim());
            string dPriceFrom =Server.HtmlEncode(Utils.KillChars(txtPriceFrom.Text.Trim().Replace(",","")));
            string dPriceTo = Server.HtmlEncode(Utils.KillChars(txtPriceTo.Text.Trim().Replace(",", "")));
            string iProductType = Server.HtmlEncode(Utils.KillChars(cboProductType.SelectedValue.ToString()));
            string strParam = Utils.RemoveUnicode(strProductName) + "@" + iProductType + "@" + dPriceFrom + "@" + dPriceTo;
            // luu noi dung searh xuong Cookie
            HttpCookie param = new HttpCookie("ParamSearch");
            param.Value = strParam;
            param.Expires = DateTime.Now.AddMinutes(3);
            Response.Cookies.Add(param);
            loadProduct(Utils.RemoveUnicode(strProductName), Convert.ToInt32(iProductType == "" ? "-1" : iProductType), Convert.ToDouble(dPriceFrom == "" ? "0" : dPriceFrom), Convert.ToDouble(dPriceTo == "" ? "500000" : dPriceTo));

        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Search Page btnSearch_Click:" + ex.Message);
        }
    }
    #region Custom Method
    private void loadProduct(string strProductName, int iProductTypeId, double dPriceFrom, double dPriceTo)
    {
        try
        {
            helper = new DatabaseHelper();
            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "IsNew";
            paramType.DbType = DbType.Int32;
            paramType.Value = 4;
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramProvinceID = helper.Parameter;
            paramProvinceID.ParameterName = "ProvinceID";
            paramProvinceID.DbType = DbType.Int32;
            paramProvinceID.Value = Convert.ToInt32(Session["ProvinceID"]);
            helper.AddParameter(paramProvinceID);

            System.Data.Common.DbParameter paramProductTypeId = helper.Parameter;
            paramProductTypeId.ParameterName = "ProductTypeId";
            paramProductTypeId.DbType = DbType.Int32;
            paramProductTypeId.Value = iProductTypeId;
            helper.AddParameter(paramProductTypeId);


            System.Data.Common.DbParameter paramProducName = helper.Parameter;
            paramProducName.ParameterName = "ProductName";
            paramProducName.DbType = DbType.String;
            paramProducName.Value = strProductName;
            helper.AddParameter(paramProducName);

            System.Data.Common.DbParameter paramPriceFrom = helper.Parameter;
            paramPriceFrom.ParameterName = "PriceFrom";
            paramPriceFrom.DbType = DbType.Double;
            paramPriceFrom.Value = dPriceFrom;
            helper.AddParameter(paramPriceFrom);

            System.Data.Common.DbParameter paramPriceTo = helper.Parameter;
            paramPriceTo.ParameterName = "PriceTo";
            paramPriceTo.DbType = DbType.Double;
            paramPriceTo.Value = dPriceTo;
            helper.AddParameter(paramPriceTo);

            System.Data.Common.DbParameter paramFunctionName = helper.Parameter;
            paramFunctionName.ParameterName = "FunctionName";
            paramFunctionName.DbType = DbType.String;
            paramFunctionName.Value = "chi-tiet-san-pham";
            helper.AddParameter(paramFunctionName);

            DataTable dt = helper.ExecuteDataTable("Web_GetProduct", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            lvProductNew.DataSource = dt;
            lvProductNew.DataBind();
            if (dt.Rows.Count == 0)
            {
                div_NoData.InnerHtml = "<BR/><B>Không tìm thấy gạo cần tìm</B>";
            }
            else
                div_NoData.InnerHtml = "";
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Search Page-loadProduct:" + ex.Message.ToString());
        }
    }
    private void createCartTable(int iProductID, string strProductName, string strProductCode, string strImagePath, double dPrice, int iWeight, int IsPromomtion = 1)
    {
        try
        {
            DataTable dt;
            if (Session["ShoppingCart"] == null)//chua ton tai san pham trong Shopping Cart
            {
                dt = new DataTable();
                dt.Columns.Add("ProductID", System.Type.GetType("System.Int32"));
                dt.Columns.Add("IsPromotion", System.Type.GetType("System.Int32"));
                dt.Columns.Add("ProductName", System.Type.GetType("System.String"));
                dt.Columns.Add("ProductCode", System.Type.GetType("System.String"));
                dt.Columns.Add("ImagePath", System.Type.GetType("System.String"));
                dt.Columns.Add("Price", System.Type.GetType("System.Double"));
                dt.Columns.Add("Weight", System.Type.GetType("System.Int32"));
                dt.Columns.Add("Amount", System.Type.GetType("System.Double"));

                DataRow drNew = dt.NewRow();
                drNew["ProductID"] = iProductID;
                drNew["IsPromotion"] = IsPromomtion;
                drNew["ProductName"] = strProductName.Trim();
                drNew["ProductCode"] = strProductCode.Trim();
                drNew["ImagePath"] = strImagePath.Trim();
                drNew["Price"] = dPrice;
                drNew["Weight"] = iWeight;
                drNew["Amount"] = iWeight * dPrice;
                dt.Rows.Add(drNew);
            }
            else//Da co san pham trong ShoppingCart
            {
                dt = (DataTable)Session["ShoppingCart"];
                if (dt.Select("ProductID=" + iProductID).Count() > 0)//Chi thay doi Shopping Cart cua san pham da ton tai
                {
                    DataRow[] rowArr = dt.Select("ProductID=" + iProductID);
                    if (rowArr.Count() > 0)
                    {
                        DataRow row = rowArr[0];
                        row["Weight"] = Convert.ToInt32(row["Weight"].ToString().Replace(",", "")) + iWeight;//tang trong luong len 1
                        row["Amount"] = Convert.ToDouble(row["Amount"]) + (Convert.ToDouble(row["Price"]) * iWeight);// tinh lai thanh tien
                    }
                }
                else
                {
                    DataRow drNew = dt.NewRow();
                    drNew["ProductID"] = iProductID;
                    drNew["IsPromotion"] = IsPromomtion;
                    drNew["ProductName"] = strProductName.Trim();
                    drNew["ProductCode"] = strProductCode.Trim();
                    drNew["ImagePath"] = strImagePath.Trim();
                    drNew["Price"] = dPrice;
                    drNew["Weight"] = iWeight;
                    drNew["Amount"] = iWeight * dPrice;
                    dt.Rows.Add(drNew);
                }

            }
            Session["ShoppingCart"] = dt;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Search Page-createCartTable:" + ex.Message.ToString());
        }
        //return dt;
    }
    #endregion End Custom Method
}